package com.wt.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wt.admin.entity.*;
import com.wt.admin.entity.rewentity.WqunBlogTagRew;
import com.wt.admin.packClass.Article;
import com.wt.admin.service.*;
import com.wt.commonutils.R;
import com.wt.oos.Upload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 管理员 前端控制器
 * </p>
 *
 * @author wt
 * @since 2023-07-14
 */
@Api(tags = "博客管理模块")
@RestController
@RequestMapping("/blog")
@CrossOrigin

public class WqunBlogController {
    @Autowired
    private WqunBlogService wqunBlogService;

    @Autowired
    private WqunBlogTagService wqunBlogTagService;

    @Autowired
    private WqunBlogLikeService wqunBlogLikeService;

    @Autowired
    private WqunBlogLookService wqunBlogLookService;

    @Autowired
    private WqunBlogCollectService wqunBlogCollectService;

    @Autowired
    private WqunArticleTagService wqunArticleTagService;

    @Autowired
    private WqunArticleTagTypeService wqunArticleTagTypeService;


    @ApiOperation("添加文章获取文章标签")
    @GetMapping("/findBolgTag")
    @PreAuthorize("hasAnyAuthority('blog:findBolgTag')")
    public R findBolgTag(){
        List<WqunBlogTagRew> findBolgTag = null;
        try {
            findBolgTag = new ArrayList<>();
            List<WqunBlogTagRew> tagRewList = new ArrayList<>();
            WqunBlogTagRew wqunBlogTagTypeRew = new WqunBlogTagRew();
            WqunBlogTagRew wqunBlogTagRew = new WqunBlogTagRew();
            QueryWrapper<WqunArticleTagType> wqunArticleTagTypeQueryWrapper = new QueryWrapper<>();
            QueryWrapper<WqunArticleTag> wqunArticleTagQueryWrapper = new QueryWrapper<>();

            wqunArticleTagTypeQueryWrapper.eq("is_delete","0");
            List<WqunArticleTagType> wqunArticleTagTypes = wqunArticleTagTypeService.list(wqunArticleTagTypeQueryWrapper);

            //组装博客标签返回体
            for (WqunArticleTagType wqunArticleTagType : wqunArticleTagTypes) {
                wqunArticleTagQueryWrapper = new QueryWrapper<>();
                //标签类型组装
                wqunBlogTagTypeRew = new WqunBlogTagRew();
                wqunBlogTagTypeRew.setValue(wqunArticleTagType.getId());
                wqunBlogTagTypeRew.setLabel(wqunArticleTagType.getName());

                //标签组装
                wqunArticleTagQueryWrapper.eq("type_id",wqunArticleTagType.getId());
                wqunArticleTagQueryWrapper.eq("is_delete","0");
                List<WqunArticleTag> wqunArticleTags = wqunArticleTagService.list(wqunArticleTagQueryWrapper);
                for (WqunArticleTag wqunArticleTag : wqunArticleTags) {
                    wqunBlogTagRew = new WqunBlogTagRew();
                    wqunBlogTagRew.setValue(wqunArticleTag.getId());
                    wqunBlogTagRew.setLabel(wqunArticleTag.getName());
                    tagRewList.add(wqunBlogTagRew);
                }
                wqunBlogTagTypeRew.setChildren(tagRewList);
                tagRewList = new ArrayList<>();//更新该类型的标签容器

                findBolgTag.add(wqunBlogTagTypeRew);
            }
        } catch (Exception e) {
            e.printStackTrace();
            R.error().message("标签查询异常，请检查网络");
        }
        return R.ok().data("findBolgTag",findBolgTag);
    }


    //查询指定id文章
    @ApiOperation("查询指定id文章")
    @GetMapping("/findArticleById/{id}/{uid}")
//    @PreAuthorize("hasAnyAuthority('blog:findArticleById')")
    public R findArticleById(@PathVariable("id") String id,@PathVariable("uid") String uid){
        //先进行用户浏览记录
        QueryWrapper<WqunBlogLook> blogLookQueryWrapper = new QueryWrapper<>();
        blogLookQueryWrapper.eq("id",uid);//用户id
        blogLookQueryWrapper.eq("blogId",id);//文章id
        WqunBlogLook one = wqunBlogLookService.getOne(blogLookQueryWrapper);
        if(one == null){//没有浏览过该博客，添加记录
            WqunBlogLook wqunBlogLook = new WqunBlogLook();
            wqunBlogLook.setId(uid);
            wqunBlogLook.setBlogId(id);
            boolean save = wqunBlogLookService.save(wqunBlogLook);

            //并且该文章的浏览数加一
            WqunBlog byId = wqunBlogService.getById(id);
            byId.setClickCount(byId.getClickCount() +1);
            boolean b = wqunBlogService.updateById(byId);
        }else{//已经浏览过，更新浏览记录
            Date date = new Date();
            one.setModifiedTime(date);
//            blogLookQueryWrapper.eq("id",uid);//用户id
//            blogLookQueryWrapper.eq("blogId",id);//文章id
//            boolean b = wqunBlogLookService.updateById(one);
            boolean update = wqunBlogLookService.update(one, blogLookQueryWrapper);
        }

        //查询文章
        QueryWrapper<WqunBlog> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", id);
        queryWrapper.eq("status",1);
//        queryWrapper.select("id","title","summary","tag_uid","click_count","like_count","collect_count","file_uid","created_time","content");
        WqunBlog wqunBlog = wqunBlogService.getOne(queryWrapper);

        //查询文章标签
        QueryWrapper<WqunBlogTag> queryWrapperTag = new QueryWrapper<>();
        QueryWrapper<WqunArticleTag> wqunArticleTagQueryWrapper = new QueryWrapper<>();
        queryWrapperTag.eq("id", id);
        queryWrapperTag.select("tag_id");
        List<WqunBlogTag> tagList = wqunBlogTagService.list(queryWrapperTag);
        String []tagAr = new String[tagList.size()];
        for (int i = 0; i < tagList.size(); i++) {
            WqunArticleTag one1 = wqunArticleTagService.getById(tagList.get(i).getTagId());
            tagAr[i] = one1.getName();
        }
        return R.ok().data("wqunBlog",wqunBlog).data("tagAr",tagAr);
    }


    //查看用户id浏览文章
    @ApiOperation("查看用户id浏览文章")
    @GetMapping("/findLookArticleById/{id}")
    @PreAuthorize("hasAnyAuthority('blog:findLookArticleById')")
    public R findLookArticleById(@PathVariable("id") String id){
        QueryWrapper<WqunBlogLook> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("blogId");
        queryWrapper.eq("id",id);
        queryWrapper.orderByDesc("modified_time");
        List<WqunBlogLook> list = wqunBlogLookService.list(queryWrapper);
        if(list.size() == 0){
            return R.error().message("您还没有浏览博客文章哦，快去浏览吧");
        }
        List<WqunBlog> findLookArticleById  = new ArrayList<>();
        for (WqunBlogLook wqunBlogLook : list) {
            QueryWrapper<WqunBlog> queryWrapper2 = new QueryWrapper();
            queryWrapper2.orderByDesc("level");
            queryWrapper2.eq("status",1);
            queryWrapper2.orderByDesc("like_count");
            queryWrapper2.eq("id",wqunBlogLook.getBlogId());
            queryWrapper2.select("id","title","summary","tag_uid","click_count","like_count","collect_count","file_uid","created_time");
            WqunBlog one = wqunBlogService.getOne(queryWrapper2);
            if(one != null){
                findLookArticleById.add(one);
            }
        }
        return R.ok().data("findLookArticleById",findLookArticleById);
    }


    //查看用户id点赞文章
    @ApiOperation("查看用户id点赞文章")
    @GetMapping("/findLikeArticleById/{id}")
    @PreAuthorize("hasAnyAuthority('blog:findLikeArticleById')")
    public R findLikeArticleById(@PathVariable("id") String id){
        QueryWrapper<WqunBlogLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("blogId");
        queryWrapper.eq("id",id);
        List<WqunBlogLike> list = wqunBlogLikeService.list(queryWrapper);
        if(list.size() == 0){
            return R.error().message("没有点赞的文章哦，快去博客添加吧");
        }
        List<WqunBlog> findLikeArticleById  = new ArrayList<>();
        for (WqunBlogLike wqunBlogLike : list) {
            QueryWrapper<WqunBlog> queryWrapper2 = new QueryWrapper();
            queryWrapper2.orderByDesc("level");
            queryWrapper2.eq("status",1);
            queryWrapper2.orderByDesc("like_count");
            queryWrapper2.eq("id",wqunBlogLike.getBlogId());
            queryWrapper2.select("id","title","summary","tag_uid","click_count","like_count","collect_count","file_uid","created_time");
            WqunBlog one = wqunBlogService.getOne(queryWrapper2);
            if(one != null){
                findLikeArticleById.add(one);
            }
        }

        return R.ok().data("findLikeArticleById",findLikeArticleById);
    }

    //查看用户id收藏文章
    @ApiOperation("查看用户id收藏文章")
    @GetMapping("/findCollectArticleById/{id}")
    @PreAuthorize("hasAnyAuthority('blog:findCollectArticleById')")
    public R findCollectArticleById(@PathVariable("id") String id){
        QueryWrapper<WqunBlogCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("blogId");
        queryWrapper.eq("id",id);
        List<WqunBlogCollect> list = wqunBlogCollectService.list(queryWrapper);
        if(list.size() == 0){
            return R.error().message("没有收藏的文章哦，快去博客收藏你的文章吧！");
        }
        List<WqunBlog> findCollectArticleById  = new ArrayList<>();
        for (WqunBlogCollect wqunBlogLike : list) {
            QueryWrapper<WqunBlog> queryWrapper2 = new QueryWrapper();
            queryWrapper2.orderByDesc("level");
            queryWrapper2.eq("status",1);
            queryWrapper2.eq("id",wqunBlogLike.getBlogId());
            queryWrapper2.orderByDesc("like_count");
            queryWrapper2.select("id","title","summary","tag_uid","click_count","like_count","collect_count","file_uid","created_time");
            WqunBlog one = wqunBlogService.getOne(queryWrapper2);
            if(one != null){
                findCollectArticleById.add(one);
            }
        }

        return R.ok().data("findCollectArticleById",findCollectArticleById);
    }

    //修改指定文章
    @ApiOperation("修改指定文章")
    @PostMapping("/updateArticle")
    @PreAuthorize("hasAnyAuthority('admin:blog:updateArticle')")
    public R updateArticle(@RequestBody Article article){
        WqunBlog wqunBlog  = article.getWqunBlog();
        String[] tagArr = article.getTagArr();
        String imgPath = wqunBlog.getFileUid();

        //博客修改
        WqunBlog byId = wqunBlogService.getById(wqunBlog.getId());
        byId.setTitle(wqunBlog.getTitle());
        byId.setContent(wqunBlog.getContent());
        byId.setSummary(wqunBlog.getSummary());
        //头像修改
        if(byId.getFileUid().equals(imgPath)){//oos图片删除
            boolean b = Upload.deleteUploadImg(byId.getFileUid());
        }
        byId.setFileUid(imgPath);


        boolean findAllArticle = wqunBlogService.updateById(byId);

        //标签删除
        QueryWrapper<WqunBlogTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",wqunBlog.getId());
        wqunBlogTagService.remove(queryWrapper);

        //标签添加
        WqunBlogTag wqunBlogTag = new WqunBlogTag();
        wqunBlogTag.setId(wqunBlog.getId());
        for (String s : tagArr) {
            wqunBlogTag.setTagId(String.valueOf(s));
            wqunBlogTagService.save(wqunBlogTag);
        }

        return findAllArticle?R.ok().message("修改文章成功"):R.error().message("文章修改失败");
    }

    //删除指定文章
    @ApiOperation("删除指定文章")
    @GetMapping("/deleteArticle/{id}")
    @PreAuthorize("hasAnyAuthority('admin:blog:deleteArticle')")
    public R deleteArticle(@PathVariable("id") String id){
        WqunBlog byId = wqunBlogService.getById(id);
        byId.setStatus(0);
        boolean findAllArticle = wqunBlogService.updateById(byId);
        return findAllArticle?R.ok().message("删除文章成功"):R.error().message("文章删除失败");
    }

    //查询所有文章
    @ApiOperation("查询所有文章")
    @GetMapping("/findAllArticle")
//    @PreAuthorize("hasAnyAuthority('blog:findAllArticle')")
    public R findAllArticle(){
//        QueryWrapper<WqunBlogTag> wqunBlogTagQueryWrapper = new QueryWrapper<>();
//        QueryWrapper<WqunArticleTag> wqunArticleTagQueryWrapper = new QueryWrapper<>();
//        List<WqunBlogTag> wqunBlogTags = wqunBlogTagService.list(wqunBlogTagQueryWrapper);
//        for (WqunBlogTag wqunBlogTag : wqunBlogTags) {
//            wqunArticleTagQueryWrapper = new QueryWrapper<>();
//            wqunArticleTagQueryWrapper.eq("name",wqunBlogTag.getTagId());
//            WqunArticleTag one = wqunArticleTagService.getOne(wqunArticleTagQueryWrapper);
//            wqunBlogTagQueryWrapper = new QueryWrapper<>();
//            wqunBlogTagQueryWrapper.eq("id",wqunBlogTag.getId());
//            wqunBlogTagQueryWrapper.eq("tag_id",wqunBlogTag.getTagId());
//            wqunBlogTag.setTagId(one.getId());
//            boolean update = wqunBlogTagService.update(wqunBlogTag,wqunBlogTagQueryWrapper);
//        }
        QueryWrapper<WqunBlog> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("level");
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("level");
        queryWrapper.orderByDesc("created_time");
        queryWrapper.select("id","title","summary","tag_uid","click_count","like_count","collect_count","file_uid","created_time");
        List<WqunBlog> allArticle = wqunBlogService.list(queryWrapper);
        return R.ok().data("userList",allArticle);
    }

    //搜索查询所有文章
    @ApiOperation("搜索查询所有文章")
    @GetMapping("/searchAllArticle/{searchValue}")
//    @PreAuthorize("hasAnyAuthority('blog:searchAllArticle')")
    public R searchAllArticle(@PathVariable("searchValue") String searchValue){

        QueryWrapper<WqunBlog> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("level");
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("level");
        queryWrapper.orderByDesc("created_time");
        queryWrapper.like("title",searchValue);
        queryWrapper.select("id","title","summary","tag_uid","click_count","like_count","collect_count","file_uid","created_time");
        List<WqunBlog> allArticle = wqunBlogService.list(queryWrapper);
        return R.ok().data("userList",allArticle);
    }



    //添加文章
    @ApiOperation("添加文章")
    @PostMapping("/addArticle")
    @PreAuthorize("hasAnyAuthority('admin:blog:addArticle')")
    public R addArticle(@RequestBody Article article){
        WqunBlog wqunBlog = article.getWqunBlog();
        String[] tagArr = article.getTagArr();
        boolean save = wqunBlogService.save(wqunBlog);
        QueryWrapper<WqunBlog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content",wqunBlog.getContent());
        queryWrapper.eq("title",wqunBlog.getTitle());
        queryWrapper.orderByDesc("id");
        queryWrapper.last("limit 1");
        WqunBlog getOne = wqunBlogService.getOne(queryWrapper);
        WqunBlogTag wqunBlogTag = new WqunBlogTag();
        wqunBlogTag.setId(getOne.getId());
        for (String s : tagArr) {
            wqunBlogTag.setTagId(String.valueOf(s));
            wqunBlogTagService.save(wqunBlogTag);
        }
        if(save){
            return R.ok().message("ok").message("发布文章成功");
        }else{
            return R.error().message("error").message("发布文章失败");
        }
    }



    @ApiOperation("点赞取消点赞")
    @PostMapping("/like")
    @PreAuthorize("hasAnyAuthority('blog:like')")
    public R like(@RequestBody WqunBlogLike wqunBlogLike){
        //修改赞数
        QueryWrapper<WqunBlogLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",wqunBlogLike.getId()).eq("blogId",wqunBlogLike.getBlogId());
        WqunBlogLike getOne = wqunBlogLikeService.getOne(queryWrapper);
        boolean res = false;
        WqunBlog wqunBlog = wqunBlogService.getById(wqunBlogLike.getBlogId());
        int likeCount = wqunBlog.getLikeCount();
        if(getOne == null){//执行点赞
            wqunBlog.setLikeCount(wqunBlog.getLikeCount()+1);
            wqunBlogLikeService.save(wqunBlogLike);//添加该用户点赞记录
            likeCount++;
        }else{//取消点赞
            wqunBlog.setLikeCount(wqunBlog.getLikeCount()-1);
            wqunBlogLikeService.remove(queryWrapper);//删除该用户点赞记录
            likeCount--;
        }
        res = wqunBlogService.updateById(wqunBlog);
        if(res){
            return R.ok().data("likeCount",likeCount);
        }else{
            return R.error();
        }

    }

    @ApiOperation("是否点赞该文章")
    @PostMapping("/isLike")
    @PreAuthorize("hasAnyAuthority('blog:isLike')")
    public R isLike(@RequestBody WqunBlogLike wqunBlogLike){
        QueryWrapper<WqunBlogLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",wqunBlogLike.getId()).eq("blogId",wqunBlogLike.getBlogId());
        WqunBlogLike getOne = wqunBlogLikeService.getOne(queryWrapper);
        if(getOne != null){
            return R.ok();
        }else{
            return R.error();
        }

    }



    @ApiOperation("点赞取消收藏")
    @PostMapping("/collect")
    @PreAuthorize("hasAnyAuthority('blog:collect')")
    public R collect(@RequestBody WqunBlogCollect wqunBlogCollect){
        //修改收藏数
        QueryWrapper<WqunBlogCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",wqunBlogCollect.getId()).eq("blogId",wqunBlogCollect.getBlogId());
        WqunBlogCollect getOne = wqunBlogCollectService.getOne(queryWrapper);
        boolean res = false;
        WqunBlog wqunBlog = wqunBlogService.getById(wqunBlogCollect.getBlogId());
        int collectCount = wqunBlog.getCollectCount();//点赞数
        if(getOne == null){//执行点赞
            wqunBlog.setCollectCount(wqunBlog.getCollectCount()+1);
            wqunBlogCollectService.save(wqunBlogCollect);
            collectCount++;
        }else{//取消点赞
            wqunBlog.setCollectCount(wqunBlog.getCollectCount()-1);
            wqunBlogCollectService.remove(queryWrapper);
            collectCount--;
        }
        res = wqunBlogService.updateById(wqunBlog);
        if(res){
            return R.ok().data("collectCount",collectCount);
        }else{
            return R.error();
        }

    }

    @ApiOperation("是否收藏该文章")
    @PostMapping("/isCollect")
    @PreAuthorize("hasAnyAuthority('blog:isCollect')")
    public R isCollect(@RequestBody WqunBlogCollect wqunBlogCollect){
        QueryWrapper<WqunBlogCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",wqunBlogCollect.getId()).eq("blogId",wqunBlogCollect.getBlogId());
        WqunBlogCollect getOne = wqunBlogCollectService.getOne(queryWrapper);
        if(getOne != null){
            return R.ok();
        }else{
            return R.error();
        }
    }


    //文章总数
    @ApiOperation("文章总数")
    @GetMapping("/AllBlogNum")
    @PreAuthorize("hasAnyAuthority('blog:AllBlogNum')")
    public R AllBlogNum(){
        QueryWrapper<WqunBlog> queryWrapper = new QueryWrapper();
        queryWrapper.eq("status",1);
        int AllBlogNum = wqunBlogService.count(queryWrapper);
        return AllBlogNum!=0?R.ok().data("AllBlogNum",AllBlogNum):R.error();
    }

}
